<?php
/**
 * 根据品类id获取商品分类以及品类的小部件
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/9/14
 * Time: 15:10
 */
namespace wap\widget;

use common\models\CustFavorite;
use common\models\GoodsBrand;
use common\models\GoodsList;
use common\models\GoodsRelation;
use Yii;
use yii\base\Widget;

class GoodsGroupWidget extends Widget{

    public $cate_id;

    public function init()
    {
        parent::init();
    }
    public function run()
    {
        $main_model = new GoodsList();
        $relation_model = new GoodsRelation();
        $where = ['use_flg'=>1,'relation_key'=>'category_'.$this->cate_id];
        $main_goods_id_list = $relation_model::find()->where($where)->orderBy('sort asc')->select('main_goods_id')->asArray()->all();
        $main_goods_id = array_column($main_goods_id_list,'main_goods_id');
        $list = $main_model::find()->where(['main_goods_id'=>$main_goods_id,'use_flg'=>1])->select('*')->limit(4)->asArray()->all();
        $result = $this->getFullGoodsList($list);
        // 渲染视图
        return $this->render('@app/views/goods/goods-group', ['list'=>$result]);
    }

    public function getFullGoodsList($main_goods_list){
        //是否已经加入心愿单
        //$master_favorite_goods_id = $this->getMasterFavorite();

        //$sale_model = new GoodsSale();
        //$goods_list = $sale_model->getMainImage($main_goods_list);

        //获取品牌信息
        $brand_model = new GoodsBrand();
        $brand_id = array_column($main_goods_list,'brand_id');
        $brand = $brand_model->getBrandListById($brand_id);
        $brand_list = array();
        foreach($brand as $value){
            $brand_list[$value['id']] = $value;
        }
        foreach($main_goods_list as &$main){
            //$main['goods_color_list'] = empty($goods_list[$main['main_goods_id']]) ? array() : $goods_list[$main['main_goods_id']];
            $main['brand_icon'] = \common\helps\tools::arrayHasValue($brand_list,'brand_id')?$brand_list[$main['brand_id']]['country_icon']:'';
            $main['brand_country_name'] = \common\helps\tools::arrayHasValue($brand_list,'brand_id')?$brand_list[$main['brand_id']]['country_name']:'';
        }

        return $main_goods_list;
    }

    //获取用户心愿单
    public function getMasterFavorite(){
        $master_favorite_goods_id = array();
        $master_info = \common\helps\tools::getloginMasterInfo();
        if(!empty($master_info)){
            $master_favorite = CustFavorite::find()->where(['cust_id'=>$master_info->id])->select('goods_id,main_goods_id')->asArray()->all();
            if(!empty($master_favorite)){
                $master_favorite_goods_id = array_column($master_favorite,'main_goods_id');
            }
        }

        return $master_favorite_goods_id;
    }
}